(function($, $page){
	var $parentGrid = $('#jGridForShifting', $page.data("_parent")), $grid = $('#gridForShiftingCopying', $page), 
	$form = $('form:first', $page), $wcTmp = $('#workcenterTemplate', $page), dateFormat = 'yyyy-MM-dd', dateTimeFormat= 'yyyy-MM-dd HH:mm', 
	perDay = 24 * 60 * 60 * 1000,
	getNextDate = function(date) {
		if (date.getTime) {
			return new Date(date.getTime() + perDay);
		} else {
			return new Date(date.parseDate(dateFormat).getTime() + perDay);
		}
	},
	columns = [
		{field: 'id', group: 'ids', type: 'checkbox', width: 22},
		{field: 'personnelCode', text: '人员编号', width: 150},
		{field: 'personnelName', text: '姓名', width: 150},
		/*{field: 'personnelTypeCode', text: '人员类型', type: 'select', width: 150},*/
		{field: 'shiftingWorkcenterCode', text: '实际工作中心', type: 'select', width: 150},
		/*{field: 'materialCode', text: '物料编号', width: 150},*/
		/*{field: 'materialText', text: '物料描述', width: 150},*/
		{field: 'startDateTime', type: 'date', format: dateTimeFormat, text: '开始时间', width: 150},
		{field: 'endDateTime', type: 'date', format: dateTimeFormat, text: '结束时间', width: 150},
		{field: 'memo', text: '备注', width: 150}
	];
	
	$grid.jGrid({
		base: hostUrl + '/shifting/',
		url: 'getShiftingsByWorkcenterAndDate',
		height: 280,
		width: 1200,
		autoLoad: false,
		columnresizeable: true,
		orderable: false,
		pageable: false,
		trselectable: false,
		hasBorder: true,
		columns: columns,
		gridbars: [
			{icon: 'add', text: '添加', target: 'confirmTodo', action: function(){
				if ($('tbody>tr>td.noData', $grid).length == 1) {
					$('tbody', $grid).empty();
				}
				appendRow($('tbody', $grid));
			}},
			{icon: 'delete', text: '移除', target: 'confirmTodo', action: function(){
				var hasSelected = false;
				$('tbody input[type=checkbox]', $grid).each(function(){
					if(this.checked){
						hasSelected = true;
						return false;
					}
				});
				if (!hasSelected) {
					alertMsg.error(DWZ.msg("alertSelectMsg"));
				} else {
					alertMsg.confirm('确认要移除选中的行吗？', {okCall: function(){
						$('tbody input[type=checkbox]', $grid).each(function(){
							if(this.checked){
								$(this).parents('tr:first').remove();
							}
						});
						$grid.jGrid('refresh');
					}});
				}
			}}
		]
	});
	/*
	$grid.on('change', '[name$=personnelCode]', function(){
		var $this = $(this), $tr = $this.parents('tr:first'), 
		$personnelType = $('[name$=personnelTypeCode]', $tr), personnelCode = this.value;
		if (personnelCode) {
			$.ajax({
				url: hostUrl + '/shifting/getPTAsByPersonnel',
				type: 'POST',
				data: {
					personnelCode: personnelCode,
				},
				dataType: 'json',
				success: function(ptas) {
					$personnelType.empty();
					var selctedIndex = -1;
					if (ptas.length) {
						$.each(ptas, function(index, pta){
							var $option = $('<option/>').attr({
								value: pta.personnelTypeCode
							}).text(pta.typeText).appendTo($personnelType);
							if (selctedIndex == -1 && pta.defaultTypeFlag == 1) {
								selctedIndex = index;
							}
							if (pta.personnelTypeCode == $personnelType.attr('sValue')) {
								selctedIndex = index;
							}
						});
					}
					$personnelType[0].selectedIndex = selctedIndex;
				},
				error: DWZ.ajaxError
			});
		} else {
			$personnelType.empty()[0].selectedIndex = -1;
		}
	});*/
	
	var rowIndex = 0, 
	trId = 'trForShiftingCopy',
	appendRow = function($tbody, obj){
		var $tr = $('<tr/>');
		$.each(columns, function(){
			var $td = $('<td/>'), $wrap = $('<div class="editCell"/>');
			if (this.type == 'checkbox') {
				var $input = $('<input type="checkbox"/>');
				$wrap.append($input);
				if (!this.group && obj) {
					$input.attr('value', obj[this.field]);
				}
			} else if (this.type == 'select') {
				var $select;
				if (this.field == 'shiftingWorkcenterCode') {
					$select = $wcTmp.clone().show().removeAttr('id');
				} else {
					$select = $('<select/>');
				}
				$wrap.append($select);
				if (obj) {
					var $op = $('>option[value=' + obj[this.field] + ']', $select);
					if ($op.length == 0) {
						$op = $('<option/>').attr('value', obj[this.field]).text(obj.shiftingWorkcenterText).appendTo($select);
					}
					$op.attr('selected', true);
					$select.attr({
						sValue: obj[this.field]
					});
				} else {
					$select[0].selectedIndex = -1;
				}
			} else if (this.type == 'date') {
				var dateFmt = this.format || 'yyyy-MM-dd',
				$input = $('<input type="text"/>').addClass('date dateInput').attr({
					dateFmt: dateFmt
				});
				$wrap.append($input).append('<a class="inputDateButton" href="javascript:;" />');
				if (obj) {
					$input.val(new Date(obj[this.field]).formatDate(dateFmt));
				}
			} else {
				var $input = $('<input type="text"/>');
				$wrap.append($input);
				if (obj) {
					$input.val(obj[this.field]);
				}
			}
			var $input = $('>select:first', $wrap);
			if($input.length == 0) {
				$input = $('>input:first', $wrap);
			}
			$input.attr({
				name: this.group || trId + rowIndex + '.' + this.field
			});
			
			var bringBackData = {
				personnelCode: obj ? obj.personnelCode : '',
				personnelName: obj ? obj.personnelName : '',
				workCenterCode: obj ? obj.workCenterCode : ''
			},
			originalCode = obj ? obj.personnelCode : '',
			theDate = $('#theDate', $form).val(), 
			nextDate = getNextDate(theDate).formatDate(dateFormat), 
			arrangedDate = $('#theArrangedDate', $form).val(),
			arrangedNextDate = getNextDate(arrangedDate).formatDate(dateFormat),
			workcenterCode = $('#workcenterCode', $form).val();
			switch (this.field) {
				case 'personnelCode':
					$input.attr({
						lookupGroup: trId + rowIndex + '_personnel',
						id: trId + rowIndex + '_personnel.personnelCode',
						labelFields: 'personnelCode,personnelName',
						postField: 'personnelCode',
						suggestFields: 'personnelCode,personnelName',
						suggestUrl: hostUrl + '/personnel/personnelSuggest?workCenterCode=' + workcenterCode,
						remote: hostUrl + '/personnel/validatePersonnel?originalCode=' + originalCode + '&workcenterCode=' + workcenterCode,
						warn: '人员编号不存在！'
					}).addClass('required').on('suggest', function() {
						if (originalCode == this.value) {
							$.bringBackSuggest(bringBackData);
						}
					});
					break;
				case 'personnelName':
					$input.attr({
						lookupGroup: trId + rowIndex + '_personnel',
						id: trId + rowIndex + '_personnel.personnelName',
						readonly:true
					});
					break;
				/*case 'materialCode':
					$input.attr({
						lookupGroup: trId + rowIndex + '_material',
						id: trId + rowIndex + '_material.materialCode',
						postField: 'materialCode',
						suggestFields: 'materialCode,materialText',
						suggestUrl: hostUrl + '/material/componentSuggest',
						remote: hostUrl + '/material/validateMaterial',
						warn: '物料不存在！'
					}).addClass('required');
					break;
				case 'materialText':
					$input.attr({
						lookupGroup: trId + rowIndex + '_material',
						id: trId + rowIndex + '_material.materialText',
						readonly:true
					});
					break;*/
				case 'startDateTime':
					$input.attr({
						dateGroup: trId + rowIndex + '_dateTime',
						minDate: theDate,
						maxDate: nextDate
					}).addClass('required from');
					var startTime = $input.val();
					if (startTime.indexOf(arrangedDate) >= 0) {
						$input.val(startTime.replace(arrangedDate, theDate));
					} else {
						$input.val(startTime.replace(arrangedNextDate, nextDate));
					}
					break;
				case 'endDateTime':
					$input.attr({
						dateGroup: trId + rowIndex + '_dateTime',
						minDate: theDate,
						maxDate: getNextDate(theDate).formatDate(dateFormat)
					}).addClass('required to');
					var endTime = $input.val();
					if (endTime.indexOf(arrangedDate) >= 0) {
						$input.val(endTime.replace(arrangedDate, theDate));
					} else {
						$input.val(endTime.replace(arrangedNextDate, nextDate));
					}
					break;
				case 'memo':
					break;
				case 'id':
					break;
				default:
					$input.addClass('required');
					break;
			}
			$td.append($wrap).appendTo($tr);
		});
		$tr.appendTo($tbody);
		if (!obj) {
			$grid.jGrid('refresh');
			$tr.initUI();
		}
		rowIndex ++;
	};
	
	var setFieldValue = function($field, obj) {
		var name = $field.attr('name');
		name = name.substring(name.indexOf('.') + 1);
		if ($field.is('.date')) {
			obj[name] = $field.val().parseDate(dateTimeFormat);
		} else {
			obj[name] = $field.val();
		}
	},
	// 判断数据列表是否无效
	validateShiftingList = function(shiftings, theDate) {
		var isInvalid = true;
		DWZ.ajax({
			url: hostUrl + '/shifting/validateShiftingList',
			async: false,
			data: {
				theDate: theDate,
				shiftings: JSON.stringify(shiftings)
			},
			alert: false,
			success: function(json) {
				isInvalid = json.data;
			}
		});
		return isInvalid;
	};
	
	$('#saveBtn', $page).on('click', function(){
		var $f = $(this).parents('form:first');
		if (!$f || !$f.valid()) {
			return false;
		}
		var shiftings = new Array(),
		theDate = $('#theDate', $form).val();
		
		$('tbody>tr', $grid).each(function(){
			var $tr = $(this);
			if ($('>.noData', $tr).length == 1) {
				alertMsg.error('无有效的数据可保存！');
				return false;
			}
			var shifting = {
				id: 0,
				theDate: theDate.parseDate(dateFormat),
				workcenterCode: $('#workcenterCode', $form).val()
			};
			$('input', $tr).each(function(){
				var $this = $(this);
				if ($this.is('[name=ids]')) {
					return true;
				}
				setFieldValue($this, shifting);
			});
			$('select', $tr).each(function(){
				setFieldValue($(this), shifting);
			});
			if (shifting.startDateTime.getTime() >= shifting.endDateTime.getTime() 
					|| shifting.endDateTime.getTime() - shifting.startDateTime.getTime() > perDay) {
				$('.date', $tr).addClass('error');
			}
			shiftings.push(shifting);
		});
		if ($('.date.error', $grid).length) {
			alertMsg.error('起止时间不合法！');
			return false;
		}
		// 如果数据校验失败
		if (validateShiftingList(shiftings, theDate)) {
			if ($('#alertMsgBox').is(':visible')) {
				return false;
			}
			alertMsg.error('数据校验失败，时间段存在冲突或者时间超过24小时，请检查数据！');
			return false;
		}
		if (shiftings.length > 0) {
			DWZ.ajax({
				url: hostUrl + '/shifting/batchSaveShiftingList',
				async: false,
				data: {
					shiftings: JSON.stringify(shiftings)
				},
				success: function(json) {
					$parentGrid.jGrid('loadData');
					$grid.jGrid('clearData');
					$('#workcenterCode', $page)[0].selectedIndex = -1;
				}
			});
		}
		return false;
	});
	
	$('#queryShiftings', $page).on('click', function(){
		var $this = $(this), postData = {};
		if ($form && $form.valid()) {
			postData.workcenterCode = $('[name=workcenterCode]', $form).val()
			postData.theDate = $('[name=theArrangedDate]', $form).val()
			$.ajax({
				url: hostUrl + '/shifting/getShiftingsByWorkcenterAndDate',
				type: 'POST',
				async: false,
				data: postData,
				dataType: 'json',
				success: function(json) {
					var $tbody = $('tbody', $grid).empty();
					rowIndex = 0;
					if (json.length) {
						$.each(json, function(index, obj){
							appendRow($tbody, obj);
						});
						$tbody.initUI();
						$('[name$=personnelCode]', $tbody).each(function(){
							$(this).change();
						});
					}
					$grid.jGrid('refresh');
				},
				error: DWZ.ajaxError
			});
		}
	});
	
	$('#closeDialog', $page).on('click', function(){
		if ($('tbody>tr>.noData', $grid).length == 1) {
			$.pdialog.close($page);
		} else {
			alertMsg.confirm('列表中的数据未保存，确认要取消吗？', {
				okCall: function(){
					$.pdialog.close($page);
				}
			});
		}
	});
	
	var today = new Date().formatDate(dateFormat);
	$('#theDate', $form).val(today).on('change', function(){
		$grid.jGrid('clearData');
		var $timeInput = $('[name$=startDateTime],[name$=endDateTime]', $grid);
		if (this.value) {
			$timeInput.attr('minDate', this.value);
			$timeInput.attr('maxDate', getNextDate(this.value).formatDate(dateFormat));
		} else {
			$timeInput.attr('minDate', today);
			$timeInput.attr('minDate', getNextDate(today).formatDate(dateFormat));
		}
	});
	
	var $aDate = $('#theArrangedDate', $form), $wCenter = $('#workcenterCode', $form);
	
	$wCenter.on('change', function(){
		$grid.jGrid('clearData');
		var value = this.value;
		if (value) {
			$.ajax({
				url: hostUrl + '/shifting/getLatestAnnangedDate',
				type: 'POST',
				async: false,
				data: {
					workcenterCode: value
				},
				dataType: 'json',
				success: function(json) {
					if (json) {
						$aDate.val(new Date(json).formatDate(dateFormat))
					} else {
						$aDate.val('');
					}
				},
				error: DWZ.ajaxError
			});
		} else {
			$aDate.val('');
		}
		return false;
	}).change();
	
})(jQuery, DWZ.context());